import React, { useState, useEffect, useDeferredValue } from "react";

const App = () => {
  const [text, setText] = useState("");
  const [arr, setArr] = useState([]);
  const [count, setCount] = useState(0);

  const handleChange = (e) => {
    setText(e.target.value);
  };

  // useDeferredValue 会延迟更新，直到下一次渲染
  // 有点像防抖，只有页面出现卡顿的时候像
  const text2 = useDeferredValue(text);

  useEffect(() => {
    setCount((v) => v + 1);
    setTimeout(() => {
      const list = [];
      for (let i = 0; i < 10; i++) {
        list.push({ id: i, text: text2 });
      }
      setArr(list);
    }, 500);
  }, [text2]);

  return (
    <>
      <h2>useDeferredValue</h2>
      <p>一共渲染了{count}次</p>
      <input type="text" value={text} onChange={handleChange} />
      <ul>
        {arr.map((item) => (
          <li key={item.id}>{item.text}</li>
        ))}
      </ul>
    </>
  );
};

export default App;
